import _ from 'lodash';
import { TIME_96, TIME_24 } from '@/pages/ETrade/components/helper';
import { getCssVariableValue } from '@/utils/utils';

// 算法
export const operators = {
  省间日前电量: 'sum',
  省间日前电价: '省间日前电费 / 省间日前电量',
  省间日前电费: 'sum',
  省间日内电量: 'sum',
  省间日内电价: '省间日内电费 / 省间日内电量',
  省间日内电费: 'sum',
  省间合计电量: 'sum',
  省内合计电价: '省内合计电费 / 省间合计电量',
  省内合计电费: 'sum',
  盈亏差额: 'sum',
  省内日前电价: '省内日前电费 / 省内日前电量',
};

//甘肃
export const gs_operators = {
  省间日前电量: {
    total: 'sum',
    point: 'any',
  },
  省间日前电价: {
    total: '省间日前电费 / 省间日前电量',
    point: 'any',
  },
  省间日前电费: {
    total: 'sum',
    point: 'any',
  },
  省间日内电量: {
    total: 'sum',
    point: 'any',
  },
  省间日内电价: {
    total: '省间日内电费 / 省间日内电量',
    point: 'any',
  },
  省间日内电费: {
    total: 'sum',
    point: 'any',
  },
  省间合计电量: {
    total: 'sum',
    point: 'any',
  },
  省内合计电价: {
    total: '省内合计电费 / 省间合计电量',
    point: 'any',
  },
  省内合计电费: {
    total: 'sum',
    point: 'any',
  },
  省内日前电量: {
    total: 'sum',
    point: 'any',
  },
  省内日前电价: {
    total: 'custom',
    point: 'custom',
  },
  省内日前电费: {
    total: 'sum',
    point: 'any',
  },
  盈亏差额: {
    total: 'sum',
    point: 'any',
  },
};
// 点位类型
export const points = [
  { label: '24', value: '24' },
  { label: '96', value: '96' },
];

// 数据类型
export const dataPoints = [
  { label: '测算数据', value: 'CS' },
  { label: '结算数据', value: 'JS' },
];

/**
 * 表格
 */
export const CODE1 = 'type';
export const tableColumns = (region) => {
  let head = [
    { code: CODE1, name: '聚合维度', width: 130, Lock: true },
    {
      name: '省间日前',
      align: 'center',
      children: [
        {
          code: '省间日前电量',
          name: '电量',
          width: 100,
          align: 'center',
          features: { sortable: true },
        },
        {
          code: '省间日前电价',
          name: '电价',
          width: 100,
          align: 'center',
          features: { sortable: true },
        },
      ],
    },
    {
      name: '省间日内',
      align: 'center',
      children: [
        {
          code: '省间日内电量',
          name: '电量',
          width: 100,
          align: 'center',
          features: { sortable: true },
        },
        {
          code: '省间日内电价',
          name: '电价',
          width: 100,
          align: 'center',
          features: { sortable: true },
        },
      ],
    },
    {
      code: region === '21' || region === '23' ? '省内实时电价' : '省内合计电价',
      name: '省内实时电价',
      width: 100,
      align: 'center',
      features: { sortable: true },
    },
    {
      code: '盈亏差额',
      name: '盈亏差额',
      width: 100,
      align: 'center',
      features: { sortable: true },
    },
  ];
  // 辽水表头
  const LNTableHeader = [
    {
      code: '省间日前盈亏差额',
      name: '省间日前盈亏差额',
      width: 100,
      align: 'center',
      features: { sortable: true },
    },
    {
      code: '省间日内盈亏差额',
      name: '省间日内盈亏差额',
      width: 100,
      align: 'center',
      features: { sortable: true },
    },
  ];
  if (region === '62') {
    head.splice(head.length - 1, 0, {
      code: '省内日前电价',
      name: '省内日前电价',
      width: 100,
      align: 'center',
      features: { sortable: true },
    });
  }
  // 辽宁和黑龙江
  if (region === '21' || region === '23') {
    head.pop();
    head.splice(head.length - 1, 0, {
      code: '省内日前电价',
      name: '省内日前电价',
      width: 100,
      align: 'center',
      features: { sortable: true },
    });
    head = [...head, ...LNTableHeader];
  }
  return head;
};
export const getTableData = (_data, _order, dataTimeOrderType, region) => {
  const { data } = _data || {};
  const head = (_data || {})?.head || (_data || {})?.meta;
  if (!_data || !data || !Object.keys(data)?.length || !head)
    return {
      tableData: [],
      exportTable: [],
    };
  const TIMELIST = dataTimeOrderType == '96' ? TIME_96 : TIME_24;
  function truncateToThreeDecimals(num, fixNum = 3) {
    if (!num && num !== 0) return '-';
    const str = num.toString();
    const [integer, decimal] = str.split('.');
    if (!decimal) return str; // 无小数部分
    return `${integer}.${decimal.slice(0, fixNum)}`; // 截取前三位
  }
  // 数据处理
  const fmtDate = (v) => v.replace(/[-]/g, '');
  const fmtRow = (_row, _title, _tag, id) => {
    let res = {
      id: id + _.uniqueId(),
      [CODE1]: _tag === '时点' ? TIMELIST[_title - 1] : _tag === '日期' ? fmtDate(_title) : _title,
    };
    head.map((k, i) => {
      let val = _row[i];
      const fixNum = k.includes('电量') ? 3 : 2;
      if (region === '21' || region === '23') {
        val = truncateToThreeDecimals(val, fixNum);
      } else val = parseFloat(parseFloat(val).toFixed(fixNum));
      res[k] = val;
    });
    return res;
  };
  // 递归种一颗树
  let exportTable = []; // 导出用
  const fn = ({ total, ...list }, title, lv, id = '') => {
    let result = fmtRow(total, title, _order[lv - 1], id);
    exportTable.push(result);
    let children = [];
    for (const k in list) {
      const temp = !!list[k]?.length
        ? fmtRow(list[k], k, _order[lv], result.id)
        : fn(list[k], k, lv + 1, result.id);

      if (
        region !== '62' ||
        !!parseFloat(temp['省间日前电量']) ||
        !!parseFloat(temp['省间日内电量'])
      ) {
        children.push(temp);
      }
      exportTable.push(temp);
    }
    if (!!children.length) {
      result.children = children.sort((a, b) => a[CODE1].localeCompare(b[CODE1], 'zh-CN'));
    }
    return result;
  };
  // 总合计要单独一行
  const { children, ...total } = fn(data, '合计', 0);
  const tableData = [total, ...(children || [])];
  return { tableData, exportTable };
};

/**
 * 图
 */
const SERIES_MAP = (region) => ({
  盈亏差额: { type: 'bar', name: '盈亏差额', color: '#F5BE15' },
  省间日前盈亏差额: { type: 'bar', name: '省间日前盈亏差额', color: '#F5BE15' },
  省间日内盈亏差额: { type: 'bar', name: '省间日内盈亏差额', color: '#E86452' },
  省间日前电价: { type: 'line', name: '省间日前电价', color: '#5E92F6' },
  省间日内电价: { type: 'line', name: '省间日内电价', color: '#E86452' },
  [region === '21' || region === '23' ? '省内实时电价' : '省内合计电价']: {
    type: 'line',
    name: '省内实时电价',
    color: '#F4903D',
  },
  省内日前电价: { type: 'line', name: '省内日前电价', color: '#837ADC' },
  省间日前电量: { type: 'bar', name: '省间日前', color: '#5B8FF9', props: { stack: 'A' } },
  省间日内电量: { type: 'bar', name: '省间日内', color: '#E86452', props: { stack: 'A' } },
});
const CHARTS_DIMS = (region) => [
  region === '21' || region === '23' ? ['省间日前盈亏差额', '省间日内盈亏差额'] : ['盈亏差额'],
  [
    '省间日前电价',
    '省间日内电价',
    region === '21' || region === '23' ? '省内实时电价' : '省内合计电价',
  ],
  ['省间日前电量', '省间日内电量'],
];

export const getCharts = (data, region) => {
  const dims = _.cloneDeep(CHARTS_DIMS(region));
  if (region === '62' || region === '21' || region === '23') dims[1].push('省内日前电价');
  return dims.map((keys) => ({
    dataset: {
      dimensions: [CODE1, ...keys],
      source: data,
    },
    series: keys.map((k) => SERIES_MAP(region)[k]),
    grid: { top: 24, left: 48, bottom: 48, right: 48 },
    tooltip: {},
    legend: {
      color: getCssVariableValue('--chart-legend-color'),
    },
    xAxis: [
      {
        type: 'category',
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
    ],
  }));
};

// 处理排序数据
export const removeEmptyRowData = (dataSource, name) => {
  const sortData = [];
  const noSortData = [];

  dataSource.map((item) => {
    if (item[name] || item[name] == 0) {
      sortData.push(item);
    } else {
      noSortData.push(item);
    }
  });
  return {
    noSortData,
    sortData,
  };
};

export const exportDataConfig = (region) => {
  let multiHeader = [
    ['聚合维度', '省间日前', '省间日前', '省间日内', '省间日内', '省内实时电价', '盈亏差额'],
  ];
  const exportMerges = ['A1:A2', 'B1:C1', 'D1:E1', 'F1:F2', 'G1:G2'];
  const header = ['聚合维度', '电量', '电价', '电量', '电价', '省内实时电价', '盈亏差额'];

  if (region === '62') {
    multiHeader[0].splice(header.length - 1, 0, '省内日前电价');
    header.splice(header.length - 1, 0, '省内日前电价');
    exportMerges.push('H1:H2');
  }
  // 辽宁和黑龙江
  if (region === '21' || region === '23') {
    header.pop();
    header.splice(header.length - 1, 0, '省内日前电价');
    header.push(...['省间日前盈亏差额', '省间日内盈亏差额']);
    multiHeader = [
      [
        '聚合维度',
        '省间日前',
        '省间日前',
        '省间日内',
        '省间日内',
        '省内日前电价',
        '省内实时电价',
        '省间日前盈亏差额',
        '省间日内盈亏差额',
      ],
    ];
    exportMerges.push('H1:H2', 'I1:I2');
  }
  return {
    multiHeader,
    exportMerges,
    // header: ['聚合维度', '电量', '电价', '电量', '电价', '省内实时电价', '盈亏差额'],
    header,
  };
};

export const OPTION_KEY = {
  交易单元: 'stationName',
  日期: 'date',
  时点: 'timeOrder',
};
